package Conprehersive1;

class Consumer implements Runnable {
    private clerk2 Clerk1;

    public Consumer(clerk2 Clerk1) {
        this.Clerk1 = Clerk1;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ":开始消费...");
        while (true) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Clerk1.Consumers();
        }
    }
}

class Productor implements Runnable {
    private clerk2 Clerk1;

    public Productor(clerk2 Clerk1) {
        this.Clerk1 = Clerk1;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ":开始生产...");
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Clerk1.Producer();
        }
    }
}

class clerk2 {
    private int product = 0;

    public synchronized void Producer() {
        if (product < 20) {
            product++;
            System.out.println(Thread.currentThread().getName() + ":开始生产第" + product + "个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void Consumers() {
        if (product > 0) {
            product--;
            System.out.println(Thread.currentThread().getName() + ":开始消费第" + (product+1) + "个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Test1 {
    public static void main(String[] args) {
        clerk2 S = new clerk2();
        Consumer c = new Consumer(S);
        Productor p = new Productor(S);
        Thread m1 = new Thread(c);
        Thread m3 = new Thread(c);
        Thread m2 = new Thread(p);
        m1.setName("消费者1");
        m2.setName("生产者1");
        m3.setName("消费者2");
        m1.start();
        m2.start();
        m3.start();


    }
}
